<template>
  <div class="container">
    <h2>宝宝喂养统计</h2>
    <div class="stats">
      <div class="stat-item">
        <span class="label">距离上次喂奶：</span>
        <span class="value">{{ lastFeedingTime }}</span>
      </div>
      <div class="stat-item">
        <span class="label">宝宝年龄：</span>
        <span class="value">{{ babyAge }}</span>
      </div>
    </div>

    <!-- 辅食统计列表 -->
    <div class="food-stats">
      <!-- 过敏食物列表 -->
      <div class="food-stat-section">
        <h3 class="section-title">⚠️ 过敏食物</h3>
        <div class="food-list">
          <div v-if="allergicFoods.length === 0" class="empty-message">
            暂无过敏食物记录
          </div>
          <div v-else>
            <div 
              v-for="food in allergicFoods" 
              :key="food.name"
              class="food-item allergic"
            >
              <span class="food-name">{{ food.name }}</span>
              <span class="food-category">[{{ food.category }}]</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 最爱食物top5 -->
      <div class="food-stat-section">
        <h3 class="section-title">😊 最爱食物 TOP5</h3>
        <div class="food-list">
          <div v-if="favoriteFoods.length === 0" class="empty-message">
            暂无喜欢的食物记录
          </div>
          <div v-else>
            <div 
              v-for="(food, index) in favoriteFoods" 
              :key="food.name"
              class="food-item favorite"
            >
              <span class="rank">{{ index + 1 }}.</span>
              <span class="food-name">{{ food.name }}</span>
              <span class="food-category">[{{ food.category }}]</span>
              <span class="food-count">{{ food.count }}次</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 不喜欢食物top5 -->
      <div class="food-stat-section">
        <h3 class="section-title">😞 不喜欢食物 TOP5</h3>
        <div class="food-list">
          <div v-if="dislikedFoods.length === 0" class="empty-message">
            暂无不喜欢的食物记录
          </div>
          <div v-else>
            <div 
              v-for="(food, index) in dislikedFoods" 
              :key="food.name"
              class="food-item disliked"
            >
              <span class="rank">{{ index + 1 }}.</span>
              <span class="food-name">{{ food.name }}</span>
              <span class="food-category">[{{ food.category }}]</span>
              <span class="food-count">{{ food.count }}次</span>
            </div>
          </div>
        </div>
      </div>
    </div>

    <!-- 30天内食物摄入分布 -->
    <div class="chart-section">
      <h3 class="section-title">🥗 30天内食物类型分布</h3>
      <div ref="pieChart" class="chart-container"></div>
    </div>

    <!-- 喂奶量图表 -->
    <div class="chart-section">
      <h3 class="section-title">📊 近7天喂奶量</h3>
      <div ref="chart" class="chart-container"></div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import * as echarts from 'echarts'
import axios from 'axios'
import dayjs from 'dayjs'

const chart = ref(null)
const pieChart = ref(null)
const lastFeedingTime = ref('0小时0分')
const babyAge = ref('0天')
const isLoading = ref(true)
const feedingRecords = ref([])
const allergicFoods = ref([])
const favoriteFoods = ref([])
const dislikedFoods = ref([])
const foodCategoryDistribution = ref([])

onMounted(async () => {
  await fetchData()
  initChart()
  initPieChart()
})

async function fetchData() {
  try {
    // 获取统计信息
    // const A = import.meta.env.VITE_API_BASE_URL;
    // console.log(A);
    const statsRes = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/stats`)
    if (statsRes.data?.age_days > 0) {
      const now = dayjs()
      const birthDate = now.subtract(statsRes.data.age_days, 'day')
      const diffYears = now.diff(birthDate, 'year')
      const diffMonths = now.diff(birthDate, 'month') % 12
      const remainingDays = now.diff(birthDate.add(diffYears, 'year').add(diffMonths, 'month'), 'day')
      babyAge.value = `${diffYears}岁${diffMonths}个月${remainingDays}天`
    } else {
      babyAge.value = '0天'
    }
    
    if (statsRes.data?.last_feeding) {
      const now = dayjs()
      // 确保后端返回的时间格式正确解析
      const lastFeeding = dayjs(statsRes.data.last_feeding, 'YYYY-MM-DD HH:mm:ss')
      const diffHours = now.diff(lastFeeding, 'hour')
      const diffMinutes = now.diff(lastFeeding, 'minute') % 60
      lastFeedingTime.value = `${diffHours}小时${diffMinutes}分`
    } else {
      lastFeedingTime.value = '0小时0分'
    }
    
    // 获取喂奶记录
    const recordsRes = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/records`)
    if (recordsRes.data?.length > 0) {
      feedingRecords.value = recordsRes.data
    } else {
      feedingRecords.value = []
    }

    // 获取辅食统计数据
    const foodStatsRes = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/complementary-food-stats`)
    if (foodStatsRes.data) {
      allergicFoods.value = foodStatsRes.data.allergic_foods || []
      favoriteFoods.value = foodStatsRes.data.favorite_foods || []
      dislikedFoods.value = foodStatsRes.data.disliked_foods || []
    }

    // 获取食物类型分布数据
    const distributionRes = await axios.get(`${import.meta.env.VITE_API_BASE_URL}/api/food-category-distribution`)
    if (distributionRes.data) {
      foodCategoryDistribution.value = distributionRes.data
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    babyAge.value = '0天'
    lastFeedingTime.value = '0小时0分'
    feedingRecords.value = []
    allergicFoods.value = []
    favoriteFoods.value = []
    dislikedFoods.value = []
    foodCategoryDistribution.value = []
  } finally {
    isLoading.value = false
  }
}

function initChart() {
  if (isLoading.value) return
  
  const myChart = echarts.init(chart.value)
  
  // 生成近一周的日期数组
  const now = dayjs()
  const weekDates = []
  for (let i = 6; i >= 0; i--) {
    weekDates.push(now.subtract(i, 'day').format('YYYY-MM-DD'))
  }
  
  // 按日期分组喂奶量
  const recordsByDate = {}
  feedingRecords.value.forEach(record => {
    if (!recordsByDate[record.date]) {
      recordsByDate[record.date] = 0
    }
    recordsByDate[record.date] += record.amount
  })
  
  // 准备图表数据 - 固定显示近一周
  const dates = weekDates
  const amounts = weekDates.map(date => recordsByDate[date] || 0)
  
  const option = {
    grid: {
      left: '8%',
      right: '8%',
      bottom: '15%',
      top: '20%',
      containLabel: true
    },
    xAxis: { 
      type: 'category', 
      data: dates,
      axisLabel: {
        rotate: 45,
        interval: 0,
        fontSize: 16 /* 图表字体统一设置为16px */
      },
      axisTick: {
        alignWithLabel: true
      }
    },
    yAxis: { 
      type: 'value',
      name: '喂奶量(ml)',
      min: 0,
      nameTextStyle: {
        fontSize: 16, /* 图表字体统一设置为16px */
        padding: [0, 0, 10, 0] /* 给Y轴标题添加下边距 */
      },
      nameLocation: 'middle',
      nameGap: 35,
      axisLabel: {
        fontSize: 16 /* 图表字体统一设置为16px */
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>喂奶量: {c}ml',
      textStyle: {
        fontSize: 16 /* 图表字体统一设置为16px */
      }
    },
    series: [{
      data: amounts, 
      type: 'line',
      smooth: true,
      itemStyle: {
        color: '#1890ff'
      },
      lineStyle: {
        width: 3 /* 增加线条宽度 */
      },
      symbolSize: 8 /* 增加数据点大小 */
    }]
  }
  myChart.setOption(option)
}

function initPieChart() {
  if (isLoading.value) return
  
  const myPieChart = echarts.init(pieChart.value)
  
  // 定义颜色数组
  const colors = ['#FF6B6B', '#4ECDC4', '#45B7D1', '#96CEB4', '#FFEAA7', '#DDA0DD', '#98D8C8', '#F7DC6F']
  
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{a} <br/>{b}: {c} ({d}%)',
      textStyle: {
        fontSize: 16
      }
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        fontSize: 14
      }
    },
    series: [
      {
        name: '食物类型',
        type: 'pie',
        radius: '70%',
        center: ['60%', '50%'],
        avoidLabelOverlap: false,
        itemStyle: {
          borderRadius: 10,
          borderColor: '#fff',
          borderWidth: 2
        },
        label: {
          show: true,
          position: 'inside',
          formatter: '{b}\n{d}%',
          fontSize: 12,
          fontWeight: 'bold',
          color: '#fff'
        },
        emphasis: {
          label: {
            show: true,
            fontSize: 14,
            fontWeight: 'bold',
            color: '#fff'
          }
        },
        labelLine: {
          show: false
        },
        data: foodCategoryDistribution.value.map((item, index) => ({
          value: item.value,
          name: item.name,
          itemStyle: {
            color: colors[index % colors.length]
          }
        }))
      }
    ]
  }
  
  myPieChart.setOption(option)
}
</script>

<style scoped>
.container {
  padding: 15px;
  margin-top: 10px;
  max-width: 100%;
  overflow-x: hidden;
}

h2 {
  font-size: 36px;
  margin-bottom: 25px;
  text-align: center;
  color: #2c3e50;
}

.stats {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-bottom: 25px;
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.stat-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 10px 0;
  border-bottom: 1px solid #eee;
}

.stat-item:last-child {
  border-bottom: none;
}

.label {
  font-weight: bold;
  color: #666;
  font-size: 24px;
}

.value {
  font-size: 28px;
  color: #42b883;
  font-weight: bold;
}

.food-stats {
  margin-bottom: 25px;
}

.food-stat-section {
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 15px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.section-title {
  font-size: 20px;
  font-weight: bold;
  margin-bottom: 15px;
  color: #2c3e50;
  border-bottom: 2px solid #eee;
  padding-bottom: 8px;
}

.food-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.food-item {
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border-radius: 8px;
  font-size: 16px;
  gap: 8px;
}

.food-item.allergic {
  background-color: #ffebee;
  border-left: 4px solid #f44336;
}

.food-item.favorite {
  background-color: #e8f5e8;
  border-left: 4px solid #4caf50;
}

.food-item.disliked {
  background-color: #fff3e0;
  border-left: 4px solid #ff9800;
}

.rank {
  font-weight: bold;
  color: #666;
  min-width: 20px;
}

.food-name {
  font-weight: bold;
  color: #2c3e50;
  flex: 1;
}

.food-category {
  color: #666;
  font-size: 14px;
}

.food-count {
  color: #42b883;
  font-weight: bold;
  font-size: 14px;
}

.empty-message {
  text-align: center;
  color: #999;
  font-style: italic;
  padding: 20px;
  font-size: 16px;
}

.chart-section {
  background-color: white;
  border-radius: 10px;
  padding: 15px;
  margin-bottom: 25px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-container {
  width: 100%;
  height: 280px; /* 增加图表高度以适应更大的字体 */
  box-sizing: border-box;
}
</style>